﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using RongCloudSms.Model;
using RongCloudSms.Service;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zop;

namespace RongCloudSms.Controllers
{
    [Route("[controller]")]
    [Authorize]
    [ApiController]
    public class RongCloudController : ControllerBase
    {
        private readonly ILogger<RongCloudController> _logger;
        private readonly IRongCloudService _service;
        public RongCloudController(ILogger<RongCloudController> logger, IRongCloudService service)
        {
            _logger = logger;
            _service = service;
        }
    
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> Notice(string signTimestamp, string nonce, string signature, [FromForm] RongCloudModel model)
        {
            var result = await _service.Check(signTimestamp, nonce, signature);
            if (!result)
            {
                _logger.LogInformation(JsonConvert.SerializeObject(model));
                _logger.LogError($"{signTimestamp},{nonce},{signature}");
                return "sign error";
            }
            await _service.Save(model);

            return "200";
        }

        [Route("[action]")]
        [HttpGet]
        public async Task<RongCloudListResponse> GetMessage(string id, long timestamp, int pagecount)
        {
            int userid = Convert.ToInt32(this.HttpContext.User.FindFirst("sub").Value);
            var result = await _service.Get(id, userid, timestamp, pagecount);
            return new RongCloudListResponse(Mapper.Map<List<RongCloudResponse>>(result.list), result.count);
        }

        [Route("[action]")]
        [HttpPost]
        public async Task<Result> GetToken(string username)
        {
            int userid = Convert.ToInt32(this.HttpContext.User.FindFirst("sub").Value);
            return await _service.GetToken(userid, username);
        }

        [Route("[action]")]
        [HttpPost]
        public async Task<Result> CreateGroup(int aduserid, int userid, string groupid, string groupname)
        {
            _logger.LogDebug($"接收创建群组请求:{groupid},{aduserid},{userid},{groupname}");
            int user_id = Convert.ToInt32(this.HttpContext.User.FindFirst("sub").Value);
            if (user_id != aduserid && userid != user_id)
                return Result.ReFailure("该用户不能创建该群组");
            return await _service.CreateGroup(aduserid, userid, groupid, groupname);
        }
    }
}